<template>
  <div v-loading="loading" class="container">
    <div slot="content" class="card-content">
      <div class="title-button">
        <el-button v-if="status && isDropshipping" type="danger" size="small" :loading="savaLoading" @click="refresh">重新拉取JD数据</el-button>
        <el-button v-if="status" type="primary" size="small" :loading="savaLoading" @click="sava">保 存</el-button>
        <el-button v-if="status" type="primary" size="small" :loading="submitExamineLoading" @click="submitExamine">{{ title }}</el-button>
      </div>
      <menuScroll ref="menuScrollRef" @changeLoading="changeLoading" @getGoodType="getGoodType" @getGoodTypeBoolean="getGoodTypeBoolean" />
    </div>
  </div>
</template>

<script>
import menuScroll from '@/views/coi/making/menuScroll.vue'
import { goodsInfosava, batchSubmitApproval, refresh } from '@/api/coi/onlineTaskAPI/sku'
import eventBus from '@/utils/eventBus'

export default {
  name: 'Making',
  components: {
    menuScroll
  },
  data() {
    return {
      loading: false,
      type: this.$route.query.type,
      id: this.$route.query.id,
      savaLoading: false,
      submitExamineLoading: false,
      isDropshipping: false,
      title: '提交审核'
    }
  },
  computed: {
    status() {
      return this.type === 'edit'
    }
  },
  mounted() {
    eventBus.$on('loadingChange', (status) => {
      this.loading = status
    })
  },
  methods: {
    changeLoading(value) {
      this.loading = value
    },
    message(message, back = false) {
      this.$message({ message, type: 'success' })
      if (back) {
        this.$router.push({
          path: this.$route.query.backPath
        })
      }
    },
    getGoodType(_) {
      this.isDropshipping = _
    },
    getGoodTypeBoolean(data) {
      console.log(data)
      if (data === 'DROPSHIPPING') {
        this.title = '发布渠道'
      }
    },
    refresh() {
      this.$confirm('此操作将重新拉取数据覆盖当前数据, 请谨慎操作, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(this.refreshRequest)
        .catch(() => {})
    },
    async refreshRequest() {
      try {
        this.loading = true
        const { code } = await refresh(this.id)
        if (code !== '0') return
        this.$message({
          type: 'success',
          message: '重拉JD数据成功!'
        })
      } finally {
        this.loading = false
        if (this.$refs.menuScrollRef && this.$refs.menuScrollRef.queryData) await this.$refs.menuScrollRef.queryData()
      }
    },
    async sava() {
      this.validate()
      const res = await this.submit()
      if (res) this.message(res)
    },
    submitExamine() {
      const _this = this

      this.$confirm('提交采购审核, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          try {
            const res1 = await _this.submit() // sava
            if (!res1) return
            const flag = _this.validate() // 校验
            if (!flag) return this.$message.error('当前页面信息填写有误！请检查修改完成后再提交！')
            _this.submitExamineLoading = true
            const { result } = await batchSubmitApproval({
              skuIds: [_this.id - 0]
            })
            if (result) {
              _this.message('提交审核成功！')
              eventBus.$emit('closeTag', this.$route)
            }
          } finally {
            _this.submitExamineLoading = false
          }
        })
        .catch(() => {})
    },
    validate() {
      const refsObject = this.$refs.menuScrollRef.$refs
      const refsKey = Object.keys(refsObject)
      const flags = refsKey.map((item) => {
        const selfRef = refsObject[item]
        if (Array.isArray(selfRef)) {
          return selfRef[0].submitForm()
        } else {
          return selfRef.submitForm()
        }
      })
      return flags.every((_) => _)
    },
    async submit() {
      try {
        this.savaLoading = true
        const info = JSON.parse(JSON.stringify(this.$refs.menuScrollRef.goodsInfo))
        if (!info.giveawayFlag) {
          if ('giveawayEffectiveDate' in info) info.giveawayEffectiveDate = null
          if ('giveawayExpiryDate' in info) info.giveawayExpiryDate = null
        }
        const goodsPhotos = this.$refs.menuScrollRef.goodsPhotos
        goodsPhotos.skuResourcesImg.forEach((item, index) => {
          item.sort = index
        })
        info.skuResources = [...goodsPhotos.skuResourcesImg, ...goodsPhotos.transparentImg]
        info.skuOptionResources = goodsPhotos.skuOptionResources
        info.skuChannelInfos.forEach((element) => {
          element.skuChannelInfo = JSON.stringify(element)
          delete element.categoryAttributeList
          delete element.channelAttributeList
        })
        const { result } = await goodsInfosava(info)
        return result
      } finally {
        this.savaLoading = false
      }
    },
    back() {
      this.$router.push({
        path: this.$route.query.backPath
      })
    },
    advertisingGuidelines() {
      const guideBaseUrl = window.appConfig.operationGuideUrl
      window.open(`${guideBaseUrl}/display/display-itemcenter.html#productguide`)
    }
  }
}
</script>

<style lang="scss">
.container {
  height: 100%;
  .card-content {
    position: relative;
    height: calc(100%);
    .title-button {
      position: absolute;
      right: 20px;
      margin-top: 25px;
    }
  }
}
.btn1 {
  margin-left: 10px;
}
</style>
